﻿using Microsoft.Extensions.Caching.Memory;
using Elight.Utility.Web;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace Elight.Utility.Extension.DataCache
{
    public class HttpRuntimeCache : ICacheService
    {
        public void Add<V>(string key, V value)
        {
            MemoryCacheHelper.GetInstance().Set(key, value, new TimeSpan(0, 20, 0));
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            MemoryCacheHelper.GetInstance().Set(key, value, new TimeSpan(0, 0, cacheDurationInSeconds));
        }

        public bool ContainsKey<V>(string key)
        {
            return MemoryCacheHelper.GetInstance().Get(key) != null ? true : false;
        }

        public V Get<V>(string key)
        {
            return (V)MemoryCacheHelper.GetInstance().Get(key);
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            return MemoryCacheHelper.GetInstance().GetCacheKeys();
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            var cacheManager = MemoryCacheHelper.GetInstance();
            if (cacheManager.GetCacheKeys().Contains(cacheKey))
            {
                return (V)cacheManager.Get(cacheKey);
            }
            else
            {
                var result = create();
                cacheManager.Set(cacheKey, result, new TimeSpan(0, 0, cacheDurationInSeconds));
                return result;
            }
        }

        public void Remove<V>(string key)
        {
            MemoryCacheHelper.GetInstance().Remove(key);
        }
    }
}
